# 导入相关的库
import json
import requests
import jieba
from wordcloud import WordCloud, ImageColorGenerator
from imageio import imread
import matplotlib.pyplot as plt

# 用户输入要爬取的歌曲ID
song_ids = input("请输入你要爬取的歌曲的id:")


# 获取歌曲内容
def get_songs(song_id):
    # 构建请求URL
    url = f'https://music.163.com/api/song/lyric?id={song_id}&lv=1&kv=1&tv=-1'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) '
                      'Chrome/90.0.4430.212 Safari/537.36',
    }
    # 发送GET请求
    res = requests.get(url=url, headers=headers)
    # 设置编码格式
    res.encoding = 'utf-8'
    # 解析JSON响应
    html = res.text
    json_obj = json.loads(html)
    # 获取歌词内容
    result = json_obj['lrc']['lyric']
    return result


# 保存歌曲到文件中
def save_song(song_id, filename):
    content = get_songs(song_id)
    with open(filename, 'a', encoding='utf-8') as file:
        file.write(content)


# 调用保存歌曲函数并打印歌曲和成功消息
save_song(2063864551, 'song.txt')
print(get_songs(2063864551))
print("爬取成功并将爬取到的歌词写入文件")

# 结巴分词和词云
my_word_path = 'dict.txt'  # 设置词典
stop_word_path = 'stopword.txt'  # 设置停用词
img_path = 'caixukun.png'  # 设置词云背景图
get_img = imread(img_path)  # 读取词云背景图
# 读取停用词列表
stopword_list = open(stop_word_path, encoding='utf-8').readlines()
stopword_list = [s.strip('\n') for s in stopword_list]
# 将停用词转换为集合
stop_words = set(stopword_list)
# 读取歌词文件并进行分词
with open('song.txt', 'r', encoding='utf-8') as file:
    song_text = file.read()
    jieba.load_userdict(my_word_path)
    # 切分文本
    song_text_1 = jieba.cut(song_text)
    song_text_2 = [s for s in song_text_1 if len(s) >= 2]
    song_text_3 = ' '.join(song_text_2)

# 生成词云图像并显示
wc = WordCloud(font_path=r'C:\Windows\Fonts\simhei.ttf', max_words=100,
               random_state=30, background_color='white', stopwords=stop_words,
               mask=get_img, max_font_size=20, scale=5, collocations=False).generate(song_text_3)
plt.imshow(wc)
plt.axis('off')
plt.show()
# 保存词云图像
wc.to_file(r'D:\PyCharm Community Edition 2024.1\pythonProject1\songs_wordcloud.jpg')
